import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';

/// 网络连接工具类
/// 提供网络状态检测和监听功能
class ConnectivityUtils {
  static final Connectivity _connectivity = Connectivity();
  static StreamSubscription<List<ConnectivityResult>>?
      _connectivitySubscription;

  /// 获取当前网络连接状态
  /// 返回网络连接结果列表
  static Future<List<ConnectivityResult>> getCurrentConnectivity() async {
    try {
      return await _connectivity.checkConnectivity();
    } catch (e) {
      return [ConnectivityResult.none];
    }
  }

  /// 判断是否有网络连接
  /// 返回true表示有网络连接，false表示无网络
  static Future<bool> isConnected() async {
    final List<ConnectivityResult> results = await getCurrentConnectivity();
    return results.isNotEmpty && !results.contains(ConnectivityResult.none);
  }



  /// 监听网络连接状态变化
  /// [onConnectivityChanged] 网络状态变化回调函数
  /// 返回StreamSubscription，可用于取消监听
  static StreamSubscription<List<ConnectivityResult>> listenConnectivityChanges(
    Function(List<ConnectivityResult>) onConnectivityChanged,
  ) {
    return _connectivity.onConnectivityChanged.listen(onConnectivityChanged);
  }

  /// 开始监听网络状态变化（全局监听）
  /// [onConnectivityChanged] 网络状态变化回调函数
  static void startListening(
    Function(List<ConnectivityResult>) onConnectivityChanged,
  ) {
    _connectivitySubscription?.cancel();
    _connectivitySubscription =
        listenConnectivityChanges(onConnectivityChanged);
  }

  /// 停止监听网络状态变化
  static void stopListening() {
    _connectivitySubscription?.cancel();
    _connectivitySubscription = null;
  }


}
